<template>
  <div>
    <div class="reptileList">
      <h3 class="title" @click="getReptileList">{{ $t("reptile.title") }}</h3>
      <div class="search">
        <el-input
          class="input-with-select"
          :placeholder="$t('reptile.search.placeholder')"
          v-model="queryInfo.query_text"
        >
          <el-select
            v-model="queryInfo.query_type"
            slot="prepend"
            style="width: 140px"
          >
            <el-option
              v-for="item in $t('reptile.options')"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>

          <i slot="prefix" class="el-input__icon el-icon-search"></i>
        </el-input>
        <el-button type="primary" @click="searchReptile">{{
          $t("reptile.search.searchBtn")
        }}</el-button>
        <el-button type="info" plain @click="resetSearch">{{
          $t("reptile.search.resetBtn")
        }}</el-button>
        <el-button
          type="success"
          plain
          icon="el-icon-circle-plus-outline"
          style="width: 300px"
          @click="createReptile()"
          >{{ $t("reptile.search.reptileCreated") }}</el-button
        >
      </div>
      <el-tabs v-model="queryInfo.reptile_type" @tab-click="handleClick">
        <el-tab-pane label="scrapyd" name="1"></el-tab-pane>
        <el-tab-pane label="python" name="2"></el-tab-pane>
        <el-tab-pane label="other" name="3"></el-tab-pane>
      </el-tabs>
      <el-table
        v-loading="loading"
        element-loading-text="Loading...."
        :data="reptileList"
        @selection-change="selectReptile"
        border
        style="margin-top: -14px; min-height: 600px"
      >
        <el-table-column
          type="index"
          :label="$t('reptile.table.index')"
          width="61"
          :index="table_index"
        >
        </el-table-column>
        <el-table-column
          type="selection"
          width="50"
          v-if="queryInfo.reptile_type == 2 ? true : false"
          key="1"
        ></el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="en_name"
          :label="$t('reptile.table.name')"
        >
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="unique"
          :label="$t('reptile.table.project')"
          width="150px"
        >
        </el-table-column>
        <!-- <el-table-column prop="cn_name" label="中文名"> </el-table-column> -->
        <el-table-column
          prop="description"
          :label="$t('reptile.table.descript')"
          show-overflow-tooltip
          v-if="queryInfo.reptile_type == 1"
          key="2"
        >
        </el-table-column>
        <!-- <el-table-column
          prop="target_url"
          :label="$t('reptile.table.URL')"
          show-overflow-tooltip
        >
        </el-table-column> -->
        <el-table-column
          prop="new_file"
          :label="$t('reptile.table.new_file')"
          show-overflow-tooltip
          v-if="queryInfo.reptile_type != 1"
          key="3"
        >
        </el-table-column>
        <!-- <el-table-column prop="state" label="状态" sortable>
          <template slot-scope="scope">
            <el-button
              v-show="scope.row.state"
              type="text"
              style="font-size: 20px; padding: 0; color: #67c23a"
              icon="el-icon-video-pause"
            ></el-button>
            <el-button
              v-show="!scope.row.state"
              style="font-size: 20px; padding: 0; color: #f56c6c; margin: 0"
              type="text"
              icon="el-icon-video-play"
            ></el-button>
          </template>
        </el-table-column> -->
        <el-table-column
          prop="warningState"
          :label="$t('reptile.table.state')"
          width="120"
        >
          <template slot-scope="scope">
            <div
              v-show="scope.row.status == 1"
              class="warningState"
              style="background-color: #f56c6c"
            ></div>
            <div
              v-show="scope.row.status == 0"
              class="warningState"
              style="background-color: #67c23a"
            ></div>
            <div
              v-show="scope.row.status == 2"
              class="warningState"
              style="background-color: #e6a23c"
            ></div>
          </template>
        </el-table-column>
        <el-table-column :label="$t('reptile.table.params')" width="100px">
          <template slot-scope="{ row }">
            <el-button
              type="warning"
              size="mini"
              plain
              @click="reptileConfig(row)"
              >{{ $t("reptile.btn.config") }}</el-button
            >
          </template>
        </el-table-column>
        <el-table-column :label="$t('reptile.table.detail')" width="150">
          <template slot-scope="scope">
            <el-button type="text" @click="reptileDetail(scope)">{{
              $t("reptile.btn.detail")
            }}</el-button>
            <el-button type="text" @click="reptileLog(scope)">{{
              $t("reptile.btn.log")
            }}</el-button>
            <!-- <el-button type="text" @click="reptileCurve(scope)"
              >统计曲线</el-button
            > -->
          </template>
        </el-table-column>
        <el-table-column :label="$t('reptile.table.operation')" width="200">
          <template slot-scope="{ row }">
            <el-button
              type="warning"
              icon="el-icon-edit"
              size="mini"
              plain
              @click="createReptile(row)"
              >{{ $t("reptile.btn.editor") }}</el-button
            >
            <el-popconfirm
              :title="$t('reptile.btn.del_sure')"
              @confirm="delReptile(row)"
            >
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                plain
                slot="reference"
                style="margin-left: 10px"
                >{{ $t("reptile.btn.delete") }}</el-button
              >
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <div class="footer">
        <!-- <el-button type="primary" size="mini" @click="reptileCurve"
          >关联爬虫统计曲线</el-button
        > -->
        <el-popover placement="top" width="260" v-model="visible">
          <el-select
            v-model="selectProject"
            :placeholder="$t('reptileDialog.form.select')"
          >
            <el-option
              v-for="item in projectOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{
                item.ip
              }}</span>
            </el-option>
          </el-select>
          <div style="text-align: right; margin: 20px 0 0 0">
            <el-button size="mini" type="text" @click="closeReptileProject">{{
              $t("reptileDialog.btn.cancel")
            }}</el-button>
            <el-button type="primary" size="mini" @click="reptileProject">{{
              $t("reptileDialog.btn.sure")
            }}</el-button>
          </div>
          <el-button
            v-show="queryInfo.reptile_type == 2 ? true : false"
            slot="reference"
            type="primary"
            size="mini"
            >{{ $t("reptileDialog.btn.project") }}</el-button
          >
        </el-popover>

        <el-pagination
          class="pagination"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.page"
          :page-size="queryInfo.pagesize"
          layout="total, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>
    <!-- <div class="reptileLogBox">
      <h3 class="title">爬虫日志</h3>
      <div class="reptileLog">
        <div class="aroundData">
          <h4 style="color: #606266">最近数据：</h4>
          <div>466549165498</div>
        </div>
        <div class="aroundLog">
          <h4 style="color: #606266">最近日志：</h4>
          <div></div>
        </div>
      </div>
    </div> -->
    <!-- 爬虫关联曲线统计图对话框 -->
    <!-- <ReptileCurveDialog
      :reptileCurveDialogVisible="reptileCurveDialogVisible"
      :selectReptileList="selectReptileList"
      @closeDialog="closeReptileCurveDialog"
    ></ReptileCurveDialog> -->
    <!-- 爬虫详情对话框 -->
    <ReptileDetailDialog
      :reptileDetailInfo="reptileDetailInfo"
      :reptileDetailDialogVisible="reptileDetailDialogVisible"
      @closeDialog="reptileDetailDialogVisible = false"
    ></ReptileDetailDialog>
    <!-- 爬虫日志对话框 -->
    <ReptileLogDialog
      :reptileLogDialogVisible="reptileLogDialogVisible"
      :reptileLogName="reptileLogName"
      :projectOptions="projectOptions"
      @closeDialog="closeLogDialog"
    ></ReptileLogDialog>
    <!-- 爬虫配置对话框 -->
    <ReptileConfigDialog
      :reptileConfigDialogVisible="reptileConfigDialogVisible"
      :reptileRow="reptileRow"
      :reptileType="queryInfo.reptile_type"
      @closeDialog="closeConfigDialog"
    ></ReptileConfigDialog>
    <!-- 创建爬虫对话框 -->
    <ReptileCreatedDialog
      :reptileCreatedDialogVisible="reptileCreatedDialogVisible"
      :editorReptileRow="editorReptileRow"
      @closeDialog="closeReptileCreatedDialog"
    ></ReptileCreatedDialog>
  </div>
</template>

<script>
import axios from "axios";
import ReptileDetailDialog from "../../../components/ReptileDetailDialog.vue";
// import ReptileCurveDialog from "../../../components/ReptileCurveDialog.vue";
import ReptileCreatedDialog from "../../../components/ReptileCreatedDialog.vue";
import ReptileLogDialog from "../../../components/ReptileLogDialog.vue";
import ReptileConfigDialog from "../../../components/ReptileConfigDialog.vue";
// import ReptileDialog from "../../../components/ReptileDialog.vue";
export default {
  components: {
    ReptileDetailDialog,
    ReptileCreatedDialog,
    ReptileLogDialog,
    ReptileConfigDialog,
  },
  data() {
    return {
      cancel: null,
      loading: true,
      visible: false,
      // 获取爬虫的参数对象
      queryInfo: {
        // 当前的页数
        page: 1,
        // 当前每页显示多少条数据
        pagesize: 10,
        query_text: "",
        query_type: 1,
        reptile_type: "1",
      },
      // 爬虫总数量
      total: 0,
      // 搜索关键字
      searchText: "",
      // 搜索条件
      select: "",
      // 打开详情弹框时 传递爬虫详细信息
      reptileDetailInfo: {},
      // 控制爬虫详情弹框显示与隐藏
      reptileDetailDialogVisible: false,
      // 控制爬虫统计曲线的显示与隐藏
      // reptileCurveDialogVisible: false,
      // 控制爬虫日志对话框的显示与隐藏
      reptileLogDialogVisible: false,
      // 控制爬虫配置对话框显示与隐藏
      reptileConfigDialogVisible: false,
      // 控制新建爬虫对话框的显示与隐藏
      reptileCreatedDialogVisible: false,
      // 所有爬虫列表
      reptileList: [],
      // 选中的爬虫列表
      selectReptileList: [],
      // 所有爬虫的数据
      // reptileListChart: [
      //   {
      //     name: "douban_spider",
      //     type: "line",
      //     // stack: "总量",
      //     data: [120, 132, 101, 134, 90, 230, 210],
      //   },
      //   {
      //     name: "test_reptile",
      //     type: "line",
      //     // stack: "总量",
      //     data: [220, 182, 191, 234, 290, 330, 310],
      //   },
      //   {
      //     name: "爬虫3",
      //     type: "line",
      //     // stack: "总量",
      //     data: [220, 100, 200, 120, 150, 330, 130],
      //   },
      // ],

      // 选中的爬虫数据
      selectReptileListChart: [],
      // 点击某一行爬虫的数据
      reptileRow: {},
      editorReptileRow: {},
      // 点击爬虫日志 传递的爬虫名参数
      reptileLogName: "",
      // 所有项目列表
      projectOptions: "",
      selectProject: "",
    };
  },
  created() {},
  mounted() {
    // console.log(this.$route.query.en_name);
    if (this.$route.query.en_name) {
      let index = this.$route.query.en_name.indexOf("/");
      this.queryInfo.query_text = this.$route.query.en_name.slice(index + 1);
    }
    this.getProjetList();
    this.getReptileList();
    // this.selectReptile([this.reptileList.data[0]]);
  },
  created() {},
  methods: {
    // 获取所有的项目列表
    async getProjetList() {
      const { data: res } = await this.$http.get("/task/list", {
        params: {
          page: 1,
          pagesize: 10,
          query_text: "",
          query_type: 1,
          task_type: 1,
        },
      });
      const { data: hostList } = await this.$http.get("/host");
      res.projects.forEach((val) => {
        console.log(val.client_id);
        val.ip = hostList.find((vals) => {
          return vals.id == val.client_id;
        }).ip;
      });
      console.log("----所有项目列表", this.projectOptions);
      console.log(res.projects);
      this.projectOptions = res.projects;
    },
    // 关闭爬虫关联项目时
    closeReptileProject() {
      this.visible = false;
      this.selectProject = "";
    },
    // 爬虫关联项目时
    async reptileProject() {
      console.log(this.selectReptileList);
      if (this.selectReptileList.length == 0)
        return this.$message.info(
          this.$t("reptileDialog.message.selectReptile")
        );
      if (this.selectProject == "")
        return this.$message.info(
          this.$t("reptileDialog.message.selectProject")
        );
      let arr = [];
      this.selectReptileList.forEach((ele) => {
        arr.push(ele.id);
      });
      console.log(arr.join(","));
      const { data: res } = await this.$http.post("related_projects", {
        project_id: this.selectProject,
        crawl_ids: arr.join(","),
      });
      if (res.code != 0)
        return this.$message.error(this.$t("reptileDialog.message.proError"));
      this.$message.success(this.$t("reptileDialog.message.proSuccess"));
      this.getReptileList();
      console.log(this.selectProject);
      console.log(this.selectReptileList);
      this.selectProject = "";
      this.visible = false;
    },
    // 爬虫总体分类变化
    handleClick() {
      this.queryInfo.page = 1;
      this.getReptileList();
    },
    // 分页功能
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.queryInfo.page = val;
      this.getReptileList();
    },
    // 取消请求的方法
    // 获取爬虫列表
    getReptileList() {
      this.loading = true;
      var that = this;
      var CancelToken = this.$http.CancelToken;

      // 取消上一次请求
      this.cancel && this.cancel("终止请求");

      this.$http
        .get("/reptile/list", {
          params: this.queryInfo,
          // 至关重要的一步
          cancelToken: new axios.CancelToken(function executor(c) {
            that.cancel = c;
          }),
        })
        .then((res) => {
          this.reptileList = res.data.data;
          this.total = res.data.total;
          this.loading = false;
        })
        .catch((err) => {
          if (axios.isCancel(err)) {
            console.log("Rquest canceled", err.message); //请求如果被取消，这里是返回取消的message
          } else {
            //handle error
            console.log(err);
          }
        });
    },
    // 爬虫详情信息
    reptileDetail(scope) {
      this.$http
        .get("/reptile/info", { params: { id: scope.row.id } })
        .then((res) => {
          // console.log(res.data);
          this.reptileDetailInfo = res.data;
          // console.log(this.reptileDetailInfo);
          this.reptileDetailDialogVisible = true;
        })
        .catch(() => {
          console.log(111);
          this.$message.error("获取爬虫详情失败");
        });
    },
    // 爬虫日志对话框
    reptileLog(scope) {
      this.reptileLogName = scope.row;
      this.reptileLogDialogVisible = true;
    },
    // 关闭爬虫日志对话框
    closeLogDialog() {
      this.reptileLogDialogVisible = false;
    },
    // 爬虫配置对话框
    reptileConfig(row) {
      // console.log(row);
      this.reptileRow = row;
      this.reptileConfigDialogVisible = true;
    },
    // 关闭爬虫配置对话框
    closeConfigDialog(val) {
      console.log(val);
      this.reptileConfigDialogVisible = false;
      if (val == 1) {
        this.getReptileList();
      }
    },
    // 搜索爬虫
    searchReptile() {
      this.getReptileList();
    },
    // 重置搜索文字
    resetSearch() {
      this.queryInfo.query_text = "";
      this.queryInfo.query_type = 1;
      this.getReptileList();
    },
    // 删除爬虫函数
    async delReptile(row) {
      console.log(row.id);
      const { data: res } = await this.$http.get("/reptile/del", {
        params: { id: row.id },
      });
      if (res.code != 0) return this.$message.error("爬虫删除失败！");
      this.$message.success("爬虫删除成功！");
      this.getReptileList();
    },
    // 打开新建爬虫对话框
    createReptile(row) {
      // console.log("新建爬虫");
      console.log(row);
      this.editorReptileRow = row;

      this.reptileCreatedDialogVisible = true;
    },
    // 关闭新建爬虫对话框
    closeReptileCreatedDialog(way) {
      this.reptileCreatedDialogVisible = false;
      if (way) return;
      this.getReptileList();
    },
    // 选中的爬虫
    selectReptile(val) {
      // console.log(val);
      this.selectReptileList = val;
      // 获取选中的爬虫
      // val.forEach((element) => {
      //   this.selectReptileList.push(element);
      // });
      // console.log(this.selectReptileList);
      // console.log(this.selectReptileList);
    },
    table_index(index) {
      return (this.queryInfo.page - 1) * this.queryInfo.pagesize + index + 1;
    },
    // 点击按钮 统计曲线对话框展示
    // reptileCurve() {
    //   if (!this.selectReptileList.length)
    //     return this.$message.warning("请选择要展示的爬虫");
    //   this.reptileCurveDialogVisible = true;
    //   // console.log(scope.row);
    // },
    // 关闭统计曲线对话框
    // closeReptileCurveDialog() {
    //   this.reptileCurveDialogVisible = false;
    // },
    // 折线图所展示的爬虫
    // selectReptile(val) {
    //   this.selectReptileList = [];
    //   // 获取选中的爬虫
    //   val.forEach((element) => {
    //     this.selectReptileList.push(element.en_name);
    //   });
    //   console.log(this.selectReptileList);
    // },
  },
};
</script>

<style lang="less" scoped>
.search {
  margin: 10px 0;
  .el-input {
    width: 34%;
  }
  .el-button {
    margin-left: 10px;
  }
}
.footer {
  display: flex;
  padding-top: 12px;
  .pagination {
    margin-left: 20px;
  }
}
.title {
  color: #606266;
}
.reptileLogBox {
  margin-top: 20px;
}
.warningState {
  margin: 3px 0;
  width: 15px;
  height: 15px;
  border-radius: 50%;
  // background-color: #ffc400;
}
.reptileLog {
  // background-color: pink;
  width: 98%;
  height: 125px;
  display: flex;
  .aroundData {
    display: flex;
    width: 50%;
    margin: 10px;
    div {
      border: 1px solid #ccc;
      border-radius: 10px;
      padding: 10px;
      width: 85%;
      // background-color: aqua;
    }
  }
  .aroundLog {
    display: flex;
    width: 50%;
    margin: 10px;
    div {
      border: 1px solid #ccc;
      border-radius: 10px;
      padding: 10px;
      width: 85%;
    }
  }
}
</style>